<template>
  <FyCurd :data="list" :option="option" :page.sync="page" @current-change="currentChange" @size-change="sizeChange">
    <template #menuLeft>
      <ElButton type="primary" size="small" icon="el-icon-upload" @click="send"> 上传服务器 </ElButton>
      <ElButton type="danger" size="small" icon="el-icon-delete" @click="clear"> 清空本地日志 </ElButton>
    </template>
    <template #type="scope">
      <ElTag type="danger" size="small">
        {{ scope.label }}
      </ElTag>
    </template>
    <template #expand="props">
      <pre class="error-stack">
        {{ props.row.stack }}
      </pre>
    </template>
  </FyCurd>
</template>

<script>
  import { mapState, mapActions, mapMutations } from 'vuex'
  import option from '@/const/logs'

  export default {
    name: 'ErrLogs',
    data() {
      return {
        // 默认不分页，若记录数超过，则分页
        onePageMaxSize: 10,
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        option,
        list: []
      }
    },
    computed: {
      ...mapState('logs', ['logsList'])
    },
    watch: {
      logsList: {
        immediate: true,
        handler: 'getList'
      }
    },
    methods: {
      ...mapActions('logs', ['sendLogs']),
      ...mapMutations('logs', ['clearLogs']),
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
        this.getList()
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage
        this.getList()
      },
      getList() {
        const total = this.logsList.left
        if (total <= this.onePageMaxSize) {
          this.list = this.logsList
        } else {
          const currentPage = this.page.currentPage
          const pageSize = this.page.pageSize
          this.list = this.logsList.slice((currentPage - 1) * pageSize, currentPage * pageSize)
          this.page.total = total
        }
      },
      send() {
        this.$confirm('确定上传本地日志到服务器?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.sendLogs.then(() => {
              this.$parent.$parent.box = false
              this.$message.success('发送成功!')
            })
          })
          .catch(() => {})
      },
      clear() {
        this.$confirm('确定清空本地日志记录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.page.currentPage = 1
            this.page.total = 0
            this.clearLogs()
            this.list = []
            this.$parent.$parent.box = false
            this.$message.success('清空成功!')
          })
          .catch(() => {})
      }
    }
  }
</script>

<style lang="scss">
  .error-stack {
    display: block;
    margin: 0 1em;
    font-size: 12px;
    font-family: monospace;
    white-space: pre;
  }
</style>
